<template>
  <div id="map" class="map"></div>
</template>

<script lang="ts" setup>
import { onMounted } from "vue";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { XYZ } from "ol/source";
import {
  olMap,
  FeatureIs,
  layer,
  addpolygon,
  createPoint,
  initMap,
  renName,
} from "../composables/useMapView.ts";
import { toLonLat } from "ol/proj";

onMounted(() => {
  let key = "c3e13f43d5f380c070aaff0b2920fae8";
  var rootLayer = new TileLayer({
    source: new XYZ({
      url:
        "http://t{0-7}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" +
        key +
        "",
    }),
  });

  olMap.value = new Map({
    target: "map",
    layers: [rootLayer, layer],
    view: new View({
      projection: "EPSG:4326",
      center: [120.51835648421402, 31.126856222408747],
      zoom: 12,
    }),
  });

  olMap.value.on("singleclick", (event) => {
    const coordinate = event.coordinate;
    var feature = olMap.value.forEachFeatureAtPixel(
      event.pixel,
      (feature) => feature
    );
    if (feature && feature.values_!.datalist) {
      renName.value = feature.values_!.datalist.name;
      FeatureIs.value.show = true;
      if (FeatureIs.value.show) {
        FeatureIs.value.x = event.pixel[0] + 50;
        FeatureIs.value.y = event.pixel[1] - 50;
      } else {
        FeatureIs.value.x = -900;
        FeatureIs.value.y = -900;
      }
      // const dom = document.querySelector(".panel-model");
      // console.log({ dom });
      // dom.style.left = event.pixel[0] + "px";
      // dom.style.top = event.pixel[1] + "px";
    }
    const [lon, lat] = toLonLat(coordinate);
    // console.log(`Longitude: ${lon}, Latitude: ${lat}`);
  });
  initMap();
  addpolygon();
  createPoint();
});
</script>

<style scoped>
.map {
  width: 100%;
  height: 100vh;
}
</style>
